/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.sys.modular.question.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.sys.modular.question.entity.Multipleselection;
import vip.xiaonuo.sys.modular.question.entity.Singleelection;
import vip.xiaonuo.sys.modular.question.enums.MultipleselectionExceptionEnum;
import vip.xiaonuo.sys.modular.question.mapper.MultipleselectionMapper;
import vip.xiaonuo.sys.modular.question.param.MultipleselectionParam;
import vip.xiaonuo.sys.modular.question.param.SingleelectionParam;
import vip.xiaonuo.sys.modular.question.service.MultipleselectionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 多选题service接口实现类
 *
 * @author lxc
 * @date 2024-02-29 10:00:15
 */
@Service
public class MultipleselectionServiceImpl extends ServiceImpl<MultipleselectionMapper, Multipleselection> implements MultipleselectionService {

    @Resource
    private MultipleselectionMapper multipleselectionMapper;

    @Override
    public PageResult<Multipleselection> page(MultipleselectionParam multipleselectionParam) {
        QueryWrapper<Multipleselection> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(multipleselectionParam)) {

            // 根据题目 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getTitle())) {
                queryWrapper.lambda().eq(Multipleselection::getTitle, multipleselectionParam.getTitle());
            }
            // 根据选项 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getFoption())) {
                queryWrapper.lambda().eq(Multipleselection::getFoption, multipleselectionParam.getFoption());
            }
            // 根据答案 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getAnswer())) {
                queryWrapper.lambda().eq(Multipleselection::getAnswer, multipleselectionParam.getAnswer());
            }
            // 根据类型 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getType())) {
                queryWrapper.lambda().eq(Multipleselection::getType, multipleselectionParam.getType());
            }
            // 根据级别 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getLevel())) {
                queryWrapper.lambda().eq(Multipleselection::getLevel, multipleselectionParam.getLevel());
            }
            // 根据状态 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getState())) {
                queryWrapper.lambda().eq(Multipleselection::getState, multipleselectionParam.getState());
            }
            // 根据备注 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getRemarks())) {
                queryWrapper.lambda().eq(Multipleselection::getRemarks, multipleselectionParam.getRemarks());
            }
            // 根据 查询
            if (ObjectUtil.isNotEmpty(multipleselectionParam.getFilepath())) {
                queryWrapper.lambda().eq(Multipleselection::getFilepath, multipleselectionParam.getFilepath());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<Multipleselection> list(MultipleselectionParam multipleselectionParam) {
        return this.list();
    }

    @Override
    public void add(MultipleselectionParam multipleselectionParam) {
        Multipleselection multipleselection = new Multipleselection();
        BeanUtil.copyProperties(multipleselectionParam, multipleselection);
        this.save(multipleselection);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<MultipleselectionParam> multipleselectionParamList) {
        multipleselectionParamList.forEach(multipleselectionParam -> {
        Multipleselection multipleselection = this.queryMultipleselection(multipleselectionParam);
            this.removeById(multipleselection.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(MultipleselectionParam multipleselectionParam) {
        Multipleselection multipleselection = this.queryMultipleselection(multipleselectionParam);
        BeanUtil.copyProperties(multipleselectionParam, multipleselection);
        this.updateById(multipleselection);
    }

    @Override
    public Multipleselection detail(MultipleselectionParam multipleselectionParam) {
        return this.queryMultipleselection(multipleselectionParam);
    }

    @Override
    public List<Map<String,Object>> getListByIds(String[] ids) {
        return multipleselectionMapper.getListByIds(ids);
    }

    /**
     * 获取多选题
     *
     * @author lxc
     * @date 2024-02-29 10:00:15
     */
    private Multipleselection queryMultipleselection(MultipleselectionParam multipleselectionParam) {
        Multipleselection multipleselection = this.getById(multipleselectionParam.getId());
        if (ObjectUtil.isNull(multipleselection)) {
            throw new ServiceException(MultipleselectionExceptionEnum.NOT_EXIST);
        }
        return multipleselection;
    }

    @Override
    public String uploadFile(MultipartFile file) {
        String msg = "success";
        try {
            Workbook workbook = null;
            //获取文件后缀名
            String suffix = file.getOriginalFilename();
            if (suffix.indexOf("xlsx") > -1) {
                workbook = new XSSFWorkbook(file.getInputStream());// 07版Excel
            } else {
                workbook = new HSSFWorkbook(file.getInputStream());// 03版Excel
            }
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {// 读取sheet
                Sheet sheet = workbook.getSheetAt(i);
                for (Row row : sheet) {// 读取行
                    if (row.getRowNum() == 0) {
                        continue;
                    }
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        if (row.getCell(j) != null) {
                            row.getCell(j).setCellType(CellType.STRING);// 将数字转换为string形式
                        }
                    }
                    if (row != null) {
                        // 存储人员信息
                        MultipleselectionParam multipleselectionParam = new MultipleselectionParam();
                        for (int k = 0; k < row.getLastCellNum(); k++) {// 读取列
                            Cell cell1 = row.getCell(k);
                            if (cell1 != null) {// 判断读取到的信息是否为空
                                String value = cell1.getStringCellValue();
                                if (!value.equals("")) {
                                    switch (k) {
                                        case 0:
                                            multipleselectionParam.setTitle(value);// 名称
                                            break;
                                        case 1:
                                            String vals = value.replace(";",",fh,");
                                            multipleselectionParam.setFoption(vals);
                                            break;
                                        case 2:
                                            multipleselectionParam.setType(value);
                                            break;
                                    }
                                }
                            }
                        }
                        boolean bol = checkParam(multipleselectionParam);// 判断是否添加过该用户
                        if(!bol){
                            Multipleselection multipleselection = new Multipleselection();
                            BeanUtil.copyProperties(multipleselectionParam, multipleselection);
                            multipleselection.setState("on");
                            this.save(multipleselection);
                        }else{
                            msg = "fail";
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
            msg = e.getMessage();
        }
        // 返回文件id
        return msg;
    }
    public boolean checkParam(MultipleselectionParam multipleselectionParam){
        List<Multipleselection> singleelections = multipleselectionMapper.queryByName(multipleselectionParam);
        boolean bol = false;
        if(singleelections.size() > 0){
            bol = true;
        }
        return bol;
    }
}
